const mysql = require('mysql2/promise');
const config = require('../config');

// 创建连接池
const pool = mysql.createPool({
  host: config.db.host,
  user: config.db.user,
  password: config.db.password,
  database: config.db.database,
  waitForConnections: true,
  connectionLimit: 10,
  queueLimit: 0
});

// 数据库工具类
class DB {
  /**
   * 执行 SQL 查询
   */
  async query(sql, values) {
    const connection = await pool.getConnection();
    try {
      const [rows] = await connection.query(sql, values);
      return [rows];
    } finally {
      connection.release();
    }
  }

  /**
   * 开始事务
   */
  async beginTransaction() {
    const connection = await pool.getConnection();
    await connection.beginTransaction();
    return connection;
  }

  /**
   * 提交事务
   */
  async commit() {
    if (this.connection) {
      await this.connection.commit();
      this.connection.release();
      this.connection = null;
    }
  }

  /**
   * 回滚事务
   */
  async rollback() {
    if (this.connection) {
      await this.connection.rollback();
      this.connection.release();
      this.connection = null;
    }
  }
}

module.exports = new DB(); 